package com.shujia.kafka

import java.util.Properties

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}

object Demo3KafkaTrans {
  def main(args: Array[String]): Unit = {

    val properties = new Properties

    //1、指定kafkabroker地址
    properties.setProperty("bootstrap.servers", "master:9092,node1:9092,node2:9092")

    //2、指定kv的序列化类
    properties.setProperty("key.serializer", "org.apache.kafka.common.serialization.StringSerializer")
    properties.setProperty("value.serializer", "org.apache.kafka.common.serialization.StringSerializer")


    properties.setProperty("transactional.id", "asdaasd")


    val producer = new KafkaProducer[String, String](properties)

    //初始化事务
    producer.initTransactions()
    //开启事务
    producer.beginTransaction()

    //数据实际上已经发送到kafka中，只是一个未提交的状态
    producer.send(new ProducerRecord[String, String]("trans", "java"))

    Thread.sleep(10000)

    producer.send(new ProducerRecord[String, String]("trans", "spark"))

    //提交事务
    producer.commitTransaction()

    producer.close()

    /**
      * kafka-console-consumer.sh --bootstrap-server  master:9092,node1:9092,node2:9092 --isolation-level read_committed  --from-beginning   --topic trans
      *
      */
  }

}
